local assert = OneRingLib.xlu.assert;

local hiddenClasses, SV = {DRUID=true, PALADIN=true, WARRIOR=true, DEATHKNIGHT=true}, {};
local pendingValue, playerName, defaultState;

local frame = ShapeshiftBarFrame;
local keeper, parent = CreateFrame("Frame"), frame:GetParent();
keeper:Hide();

local function SetStanceBarVisibility(shown)
	assert(type(shown) == "boolean", "Syntax: SetStanceBarVisibility(shown); %q", 2, tostring(shown));
	if InCombatLockdown() then
		pendingValue = shown;
	else
		frame:SetParent(shown and parent or keeper);
		if shown and frame:IsShown() then frame:Show(); end
		pendingValue = nil;
	end
	if shown == defaultState then shown = nil; end
	SV[playerName] = shown;
end
local function GetStanceBarVisibility()
	if pendingValue ~= nil then
		return pendingValue;
	end
	return frame:GetParent() == parent;
end
local function syncPending(event)
	if pendingValue ~= nil then
		SetStanceBarVisibility(pendingValue);
	end
end
local function notifier(event)
	if event == "LOADED" then
		defaultState = not hiddenClasses[select(2, UnitClass("player"))];
		local state = defaultState;
		playerName = GetRealmName() .. "-" .. UnitName("player");
		if type(SV[playerName]) == "boolean" then state = SV[playerName]; end
		SetStanceBarVisibility(state);
	end
end
local function IsValidPlayerClass()
	return hiddenClasses[select(2, UnitClass("player"))] ~= nil;
end

OneRingLib.ext.StanceBar = {
	SetVisibility=SetStanceBarVisibility,
	GetVisibility=GetStanceBarVisibility,
	IsUsed=IsValidPlayerClass
};

OneRingLib:RegisterPVar("StanceBar", SV, notifier);
EC_Register("PLAYER_REGEN_ENABLED", "OPie.StanceBar.Combat", syncPending);